<?php

namespace App\Jobs;

use App\Exports\InvoicesExport;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Maatwebsite\Excel\Facades\Excel;

class ExportsExcelJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $exports;
    public $fileName;
    public $headings;
    public $startCell;
    public $ext;
    public function __construct(array $exports, string $fileName, $headings = [], string $startCell = 'A1', string $ext = 'csv')
    {
        $this->exports = $exports;
        $this->fileName = $fileName;
        $this->headings = $headings;
        $this->startCell = $startCell;
        $this->ext = $ext;
    }

    public function handle()
    {
        try {
            echo '执行开始,导出excel:'."\n";
            $export = new InvoicesExport($this->exports, $this->headings, $this->startCell);
            Excel::store($export, $this->fileName.'.'.$this->ext);
        } catch (\Exception $e) {
            echo '执行错误'.date('Y-m-d H:i:s', time())."\n";
            \Log::channel('jobLog')->error('导出excel错误：'.$e);
        }

    }

    /**
     * 任务未能处理
     *
     * @param \Exception $exception
     * @return void
     */
    public function failed(\Exception $exception)
    {
        // 给用户发送失败通知, 等等...
//        \Log::channel('jobLog')->error('导出excel错误：'.$exception);
    }
}
